package pub.pjoc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author xiongyingqi
 * @since 16-9-9 上午10:32
 */
public abstract class NetWorkUtils {
  private static final Logger logger = LoggerFactory.getLogger(NetWorkUtils.class);

  public static InetAddress getInetAddress() throws UnknownHostException {
    return InetAddress.getLocalHost();
  }

  public static String getHostIp(InetAddress netAddress) {
    if (null == netAddress) {
      return null;
    }
    String ip = netAddress.getHostAddress(); //get the ip address
    return ip;
  }

  /**
   * 获取等宽的机器码，相同的机器每次都是获取相同值
   *
   * @return
   */
  public static String getWidthMachineNumber() throws UnknownHostException {
    return getWidthMachineNumber(maxWidth());
  }

  /**
   * 获取等宽的机器码，相同的机器每次都是获取相同值
   *
   * @return
   */
  public static String getWidthMachineNumber(int maxWidth) throws UnknownHostException {
    String hostName = getHostName();
    if (hostName == null) {
      return null;
    }
    int hash = hostName.hashCode();
    long unsignedHash = getUnsignedInt(hash);
    String machineNo = unsignedHash + "";
    int least = maxWidth - machineNo.length();
    if (least > 0) {
      for (int i = 0; i < least; i++) {
        machineNo = "0" + machineNo;
      }
    }
    return machineNo;
  }

  /**
   * Returns a hash code for this string. The hash code for a
   * {@code String} object is computed as
   * <blockquote><pre>
   * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
   * </pre></blockquote>
   * using {@code int} arithmetic, where {@code s[i]} is the
   * <i>i</i>th character of the string, {@code n} is the length of
   * the string, and {@code ^} indicates exponentiation.
   * (The hash value of the empty string is zero.)
   *
   * @return a hash code value for this object.
   */
  public static int stringHashCode(String string) {
    int h = 0;
    char[] value = string.toCharArray();
    if (h == 0 && value.length > 0) {
      char val[] = value;

      for (int i = 0; i < value.length; i++) {
        h = 31 * h + val[i];
      }
    }
    return h;
  }

  public static int byteArrayHashCode(byte[] bytes) {
    int h = 0;
    if (h == 0 && bytes.length > 0) {
      byte[] val = bytes;

      for (int i = 0; i < bytes.length; i++) {
        h = 31 * h + val[i];
      }
    }
    return h;
  }

  private static int maxWidth() {
    return (Integer.MAX_VALUE + "").length();
  }

//    public static String getHardWareAddress() throws SocketException, UnknownHostException {
//        for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
//                .getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
//            NetworkInterface networkInterface = networkInterfaces.nextElement();
//            byte[] hardwareAddress = networkInterface.getHardwareAddress();
//            if (hardwareAddress != null) {
//                System.out
//                        .println("hardwareAddress=========" + numericToMac(hardwareAddress));
//            }
//            System.out.println(networkInterface.getName());
//            System.out.println(networkInterface.getDisplayName());
//            System.out.println(networkInterface.getMTU());
//            System.out.println("virtual: " + networkInterface.isVirtual());
//            System.out.println("loopback: " + networkInterface.isLoopback());
//            System.out.println("p2p: " + networkInterface.isPointToPoint());
//            System.out.println("up: " + networkInterface.isUp());
//        }
//        return null;
//    }

  public static String getHostName() throws UnknownHostException {
    return getHostName(getInetAddress());
  }

  public static String getHostName(InetAddress netAddress) {
    if (null == netAddress) {
      return null;
    }
    String name = netAddress.getHostName(); //get the host address
    return name;
  }

  static String numericToTextFormat(byte[] src) {
    System.out.println("length==" + src.length);
    return (src[0] & 0xff) + "." + (src[1] & 0xff) + "." + (src[2] & 0xff) + "." + (src[3]
        & 0xff);
  }

  static String numericToMac(byte[] src) {
    if (src.length == 6) {
      StringBuilder builder = new StringBuilder();
      for (byte b : src) {
        builder.append(Integer.toHexString(b & 0xff));
      }
      return builder.toString();
    }
    return null;
  }

  public static long getUnsignedInt(int x) {
    return x & 0x00000000ffffffffL;
  }

  public static void main(String[] args) throws IOException {
    String hostName = getHostName(getInetAddress());
    System.out.println(hostName.hashCode());
    System.out.println(stringHashCode(hostName));
    System.out.println(Integer.MAX_VALUE);
    System.out.println(getWidthMachineNumber());
  }

}
